package com.cali.common.kt

import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.net.URL
import javax.net.ssl.HttpsURLConnection

fun <T> T?.jsonBody() = RequestBody.create(
    MediaType.parse("application/json;charset=utf-8"),
    Gson().toJson(this))


@Throws(Exception::class)
fun URL.get(block:(result:String) -> Unit){
    val url = this
    GlobalScope.launch(Dispatchers.IO){
        val conn = url.openConnection() as HttpsURLConnection
        if (conn.responseCode == 200) {
            val ins = conn.inputStream
            val out = ByteArrayOutputStream()
            val buffer = ByteArray(1024)
            var len: Int
            while (-1 != (ins.read(buffer)).also { len = it }) {
                out.write(buffer, 0, len)
                out.flush()
            }
            launch(Dispatchers.Main) {
                block(out.toString("utf-8"))
            }
        }
    }

}

// 文件写入流
fun File.writeInputStream(ins: InputStream) {
    var fos: FileOutputStream? = null
    val buffer = ByteArray(1024)
    var len: Int
    try {
        fos = FileOutputStream(this)
        while (ins.read(buffer).also { len = it } != -1) {
            fos.write(buffer, 0, len)
        }
    } catch (e: Exception) {

    } finally {
        ins.close()
        fos?.close()
    }
}